#include<iostream>
#include<sys/socket.h>
#include<cstring>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<string>

using namespace std;
void Usage(string proc)
{
    cout<<"Usage:"<<proc<<"server_ip server_prot"<<endl;
}

// ./tcp_client server_ip server_prot
int main(int argc, char* argv[])
{
    if(argc!=3){
        Usage(argv[2]); return 1;
    }
    string ser_ip=argv[1];
    uint16_t ser_port=(uint16_t)atoi(argv[2]);

    //1.创建socket
    int sock=socket(AF_INET,SOCK_STREAM,0);
    if(sock<0){
        cerr<<"socket error"<<endl; return 2;
    }

    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family=AF_INET;

    //(1). 将点分十进制的字符串风格的IP，转化成为4字节IP
    //(2). 将4字节由主机序列转化成为网络序列
    server.sin_addr.s_addr=inet_addr(ser_ip.c_str());
    server.sin_port=htons(ser_port);

    //2connect
    if(connect(sock,(struct sockaddr*)&server,sizeof(server))<0)
    {
        cerr<<"connect error"<<endl; return 3;
    }
    cout<<"connet success!!!"<<endl;

    while(true)
    {
       cout<<"Please Enter#";
       char buffer[1024];
       fgets(buffer,sizeof(buffer)-1,stdin);

       write(sock,buffer,strlen(buffer)); 
       ssize_t s=read(sock,buffer,sizeof(buffer)-1);
       
       if(s>0){
        buffer[s]=0;
        cout<<"server echo"<<buffer<<endl;
       }
    }
    return 0;

}